import path from 'node:path';
import fs from 'node:fs';

export function resolveModelPath(modelOrPath: string): string {
  if (modelOrPath.endsWith('.ts')) {
    return path.resolve(process.cwd(), modelOrPath);
  }
  // try default src/models
  return path.resolve(process.cwd(), 'src', 'models', `${modelOrPath.replace(/\.model$/, '')}.model.ts`);
}

export function readFile(filePath: string): string {
  if (!fs.existsSync(filePath)) {
    throw new Error(`Model file not found: ${filePath}`);
  }
  return fs.readFileSync(filePath, 'utf-8');
}

export function ensureDir(dir: string) {
  fs.mkdirSync(dir, { recursive: true });
}

export function writeFileOnce(file: string, content: string) {
  if (fs.existsSync(file)) {
    throw new Error(`File already exists: ${file}`);
  }
  fs.writeFileSync(file, content, 'utf-8');
}

export function updateExportFile(exportFilePath: string, itemName: string, itemImportPath: string) {
  // 确保文件存在
  if (!fs.existsSync(exportFilePath)) {
    // 创建初始文件内容
    const initialContent = `export const ${exportFilePath.includes('module') ? 'indexModules' : 'indexModels'} = [\n];\n`;
    fs.writeFileSync(exportFilePath, initialContent, 'utf-8');
  }

  let content = fs.readFileSync(exportFilePath, 'utf-8');
  
  // 添加导入语句
  const importLine = `import { ${itemName} } from '${itemImportPath}';`;
  if (!content.includes(importLine)) {
    content = importLine + '\n' + content;
  }
  
  // 在数组中添加项目
  const arrayName = exportFilePath.includes('module') ? 'indexModules' : 'indexModels';
  const arrayRegex = new RegExp(`(export const ${arrayName} = \\[)([\\s\\S]*?)(\\];)`, 'm');
  const match = content.match(arrayRegex);
  
  if (match) {
    const existingItems = match[2];
    if (!existingItems.includes(itemName)) {
      // 解析现有项目
      const items = existingItems
        .split(',')
        .map(item => item.trim())
        .filter(item => item.length > 0);
      
      // 添加新项目
      items.push(itemName);
      
      // 重新构建数组
      const updatedItems = items.length > 0 ? '\n    ' + items.join(',\n    ') + ',\n' : '\n';
      const updatedArray = `export const ${arrayName} = [${updatedItems}];`;
      
      content = content.replace(arrayRegex, updatedArray);
    }
  }
  
  fs.writeFileSync(exportFilePath, content, 'utf-8');
}